package thread;

import java.util.concurrent.*;

public class ThreadCreatTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 继承Thread类
        MyThread thread = new MyThread();
        thread.setName("测试MyThread");
        thread.start();

        // 实现Runnable接口
        MyRunnable myRunnable = new MyRunnable();
        Thread thread1 = new Thread(myRunnable,"测试Runnable接口线程");
        thread1.start();

        // 实现Callable接口
        MyCallable myCallable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
        Thread thread2 = new Thread(futureTask,"测试Callable接口线程");
        thread2.start();
        Integer integer = futureTask.get();
        System.out.println("FutureTask 返回结果"+integer);

        // 线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,
                10,
                1000,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(),
                new MyThreadFactory("my ThreadPool"),
                new ThreadPoolExecutor.AbortPolicy());
        for (int i=0; i<10; i++){
            int finalI = i;
            threadPoolExecutor.execute(()->{
                System.out.println(Thread.currentThread().getName() + " "+ finalI);
            });
        }

    }


    /**
     * 创建多线程的方式
     */

    //1. 继承Thread类
    static class MyThread extends Thread{
        @Override
        public void run() {
            for (int i=0; i<10; i++){
                System.out.println(getName() + ":" + i);
            }
        }
    }

    //2. 实现Runnable接口
    static class MyRunnable implements Runnable{
        @Override
        public void run() {
            for (int i=0; i<10; i++){
                System.out.println(Thread.currentThread().getName() +":"+i);
            }
        }
    }

    //3. 实现Callable接口
    static class MyCallable implements Callable{

        @Override
        public Object call() throws Exception {
            int sum=0;
            for (int i=0; i<10; i++){
                System.out.println(Thread.currentThread().getName() +":" +i);
                sum+=i;
            }
            return sum;
        }
    }






}
